using System;
using System.IO;
using System.Threading;
using System.Xml.Linq;

namespace OracleInternal.Common
{
	internal class FileWatcher : IDisposable
	{
		private FileSystemWatcher m_watcher;

		private DateTime m_lastWriteTime;

		private int m_hashCode;

		internal bool m_setUp;

		internal FileWatcher(string path)
		{
			if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
			{
				m_watcher = new FileSystemWatcher
				{
					Path = Path.GetDirectoryName(path),
					Filter = Path.GetFileName(path),
					NotifyFilter = NotifyFilters.LastWrite
				};
				m_watcher.Changed += OnFileChangedNotificationReceived;
				m_watcher.EnableRaisingEvents = true;
				m_setUp = true;
			}
			else
			{
				m_setUp = false;
			}
		}

		private void OnFileChangedNotificationReceived(object sender, FileSystemEventArgs e)
		{
			string fullPath = e.FullPath;
			DateTime lastWriteTime = File.GetLastWriteTime(fullPath);
			if (lastWriteTime == m_lastWriteTime)
			{
				return;
			}
			m_lastWriteTime = lastWriteTime;
			string text = null;
			try
			{
				text = XElement.Load(fullPath).Element("oracle.manageddataaccess.client").ToString();
			}
			catch
			{
				text = null;
			}
			if (!string.IsNullOrWhiteSpace(text))
			{
				int hashCode = text.GetHashCode();
				if (m_hashCode != hashCode)
				{
					m_hashCode = hashCode;
					m_watcher.EnableRaisingEvents = false;
					ThreadPool.QueueUserWorkItem(new WaitCallback(OnAppConfigFileChanged));
				}
			}
		}

		private void OnAppConfigFileChanged(object state)
		{
			try
			{
				ProviderConfig.OnAppConfigFileChanged();
			}
			catch
			{
			}
			finally
			{
				if (m_watcher != null)
				{
					m_watcher.EnableRaisingEvents = true;
				}
			}
		}

		public void Dispose()
		{
			if (m_watcher == null)
			{
				return;
			}
			try
			{
				m_watcher.EnableRaisingEvents = false;
				m_watcher.Changed -= OnFileChangedNotificationReceived;
				m_watcher.Dispose();
			}
			catch
			{
			}
			finally
			{
				m_watcher = null;
			}
		}
	}
}
